//
//  MemorizeWordsViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/19.
//

#import "MemorizeWordsViewController.h"
#import "ZLSwipeableView.h"
#import "WordsCardView.h"
#import "WordErrorViewController.h"
#import "WordListModel.h"
#import "SearchViewController.h"
#import "ReciteWordManager.h"
#import "WordListOrderManager.h"
#import "CollectSaveManager.h"
#import "WordCollectDeleteManager.h"
#import "WordTestManager.h"
#import "WordStateTestUpdateManager.h"
#import "SummaryViewController.h"
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"

@interface MemorizeWordsViewController()<
ZLSwipeableViewDataSource,
ZLSwipeableViewDelegate,
ZLSwipeableViewAnimator,
WordsCardViewDelegate,
JPAPIManagerCallBackDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate
>

@property(nonatomic,strong)ZLSwipeableView *swipeableView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,strong)UIView *searchBgView;
@property(nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong)ReciteWordManager *reciteWordManager;
@property(nonatomic,strong)WordListOrderManager *wordListOrderManager;
@property(nonatomic,strong)CollectSaveManager *collectSaveManager;
@property(nonatomic,strong)WordsCardView *collectWordsCardView;
@property(nonatomic,strong)WordCollectDeleteManager *collectDeleteManager;
@property(nonatomic,assign)NSInteger initCount;
@property(nonatomic,strong)WordTestManager *wordTestManager;
@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,assign)NSInteger isTest;//是否是测试模式
@property(nonatomic,assign)NSInteger correctCount;//测试了的单词个数
@property(nonatomic,copy)NSString *sumCount;
@property(nonatomic,strong)WordStateTestUpdateManager *stateTestUpdateManager;
@property(nonatomic,assign)NSInteger testCount;//测试了的数量
@property(nonatomic,strong)NSMutableString *wordIds;
@property(nonatomic,assign)BOOL isjump;//跳转去小结
@property(nonatomic,strong)WordsCardView *firstCardView;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property(nonatomic,strong)dispatch_queue_t work_queue;
@property(nonatomic,strong)WordsCardView *speakCardView;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)UIImageView *topImageView;
@property(nonatomic,assign)BOOL isRefreshWidth;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property (nonatomic,assign) BOOL isPlaying;


@end

@implementation MemorizeWordsViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(ReciteWordManager *)reciteWordManager{
    if(!_reciteWordManager){
        _reciteWordManager = [[ReciteWordManager alloc]init];
        _reciteWordManager.delegate = self;
    }
    return _reciteWordManager;
}

-(WordListOrderManager *)wordListOrderManager{
    if(!_wordListOrderManager){
        _wordListOrderManager = [[WordListOrderManager alloc]init];
        _wordListOrderManager.delegate = self;
    }
    return _wordListOrderManager;
}

-(CollectSaveManager *)collectSaveManager{
    if(!_collectSaveManager){
        _collectSaveManager = [[CollectSaveManager alloc]init];
        _collectSaveManager.delegate = self;
    }
    return _collectSaveManager;
}

-(WordCollectDeleteManager *)collectDeleteManager{
    if(!_collectDeleteManager){
        _collectDeleteManager = [[WordCollectDeleteManager alloc]init];
        _collectDeleteManager.delegate = self;
    }
    return _collectDeleteManager;
}

-(WordTestManager *)wordTestManager{
    if(!_wordTestManager){
        _wordTestManager = [[WordTestManager alloc]init];
        _wordTestManager.delegate = self;
    }
    return _wordTestManager;
}

-(WordStateTestUpdateManager *)stateTestUpdateManager{
    if(!_stateTestUpdateManager){
        _stateTestUpdateManager = [[WordStateTestUpdateManager alloc]init];
        _stateTestUpdateManager.delegate = self;
    }
    return _stateTestUpdateManager;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    self.initCount = 0;
    self.isTest = NO;
    self.isPlaying = NO;
    [self initPlay];
    [self NuiTtsInit];
    [self createUI];
    [self loadReciteWordData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(summaryClose) name:@"SummaryClose" object:nil];
    
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
}


#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("MemorizeWordsViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}

#pragma mark - 更新语音合成参数配置
-(void)UpdateTtsParams:(NSString *)content{
    
    int chars = 0;
    // 支持一次性合成300字符以内的文字，其中1个汉字、1个英文字母或1个标点均算作1个字符，
    // 超过300个字符的内容将会截断。所以请确保传入的text小于300字符(不包含ssml格式)。
    // 长短文本语音合成收费不同，请注意。
    // 300字这个截点可能会变更，以官网文档为准。
    chars = [self.nui nui_tts_get_num_of_chars: [content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成 长文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成 短文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}

#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.speakCardView){
                    [self.speakCardView stopPlayAnimation];
                }
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
           
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.speakCardView){
            [self.speakCardView stopPlayAnimation];
        }
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.speakCardView){
                [self.speakCardView stopPlayAnimation];
            }
        }
    });

}

#pragma mark - 语音合成读文本
-(void)speakText:(WordsCardView *)wordsCardView andText:(nonnull NSString *)text{
   self.speakCardView = wordsCardView;
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            if(self.nui){
                // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
                [self.nui nui_tts_cancel:NULL];
                
                [self UpdateTtsParams:text];
                
                [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
            }
        });
    }

}

#pragma mark - 停止语音播放
-(void)stopSpeak:(WordsCardView *)wordsCardView{
    
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        [self.avPlayer seekToTime:kCMTimeZero];
    }
}


#pragma mark - 单词音频播放
-(void)playAudio:(WordsCardView *)wordsCardView andAudio:(NSString *)audio{
    self.speakCardView = wordsCardView;
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:audio]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    if(self.avPlayer){
        [self.avPlayer pause];
        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
    }else{
        self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    [self.avPlayer play];
    self.isPlaying = YES;
}

-(void)playToEndTime:(NSNotification*)notifi{
    if(self.speakCardView){
        [self.speakCardView stopPlayAnimation];
    }
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            [JPProgressHUD showMsg:@"播放失败"];
            if(self.speakCardView){
                [self.speakCardView stopPlayAnimation];
            }
        }
    }
}


#pragma mark - 登录过期 退出登录
-(void)needLogin{
    if([[self currentViewController] isKindOfClass:[MemorizeWordsViewController class]]){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - 测完最后的小结关闭页面
-(void)summaryClose{
    __weak typeof(self)weakSelf = self;
    [self dismissViewControllerAnimated:NO completion:^{
        if(weakSelf.refrehBlock){
            weakSelf.refrehBlock();
        }
    }];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGFloat h636 = [DeviceUtils getAdaptedWidthForDesignWidth:636 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(h636 > self.currentAvailableHeight){
        h636 = self.currentAvailableHeight;
    }
    UIImageView *topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,h636)];
    topImageView.userInteractionEnabled = YES;
    topImageView.image = [UIImage imageNamed:@"memorize_words_top_bg"];
    [self.view addSubview:topImageView];
    self.topImageView = topImageView;
    
    UIButton *closeBtn = [[UIButton alloc]init];
    [closeBtn setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@44);
        make.left.mas_equalTo(@6);
        make.bottom.mas_equalTo(@2);
    }];
    
    self.searchBgView = [[UIView alloc]init];
    self.searchBgView.backgroundColor = UIColorHex_(0xffffff,0.6);
    self.searchBgView.layer.cornerRadius = 18;
    self.searchBgView.layer.masksToBounds = YES;
    [self.customNavigationBar addSubview:self.searchBgView];
    [self.searchBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@52);
        make.right.mas_equalTo(@-38);
        make.bottom.mas_equalTo(@-2);
        make.height.mas_equalTo(@36);
    }];
    __weak typeof(self)weakSelf = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        SearchViewController *vc = [[SearchViewController alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    [self.searchBgView addGestureRecognizer:tap];
    
    UIImageView *logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(17,10.5,15,15)];
    logoImageView.image = [UIImage imageNamed:@"area_search"];
    logoImageView.userInteractionEnabled = YES;
    [self.searchBgView addSubview:logoImageView];
    UILabel *searchTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(42,8,100,20)];
    searchTitleLabel.font = JPUIFontPingFangSCRegular(14);
    searchTitleLabel.textColor = KFontGrayColor;
    searchTitleLabel.userInteractionEnabled = YES;
    searchTitleLabel.text = @"查询中文或日文";
    [self.searchBgView addSubview:searchTitleLabel];
    
    self.progressView = [[UIProgressView alloc]init];
    self.progressView.backgroundColor = UIColorHex_(0xffffff,0.6);
    self.progressView.layer.cornerRadius = 4;
    self.progressView.layer.shadowColor = UIColorHex_(0x15CB9C,0.15).CGColor;
    self.progressView.layer.shadowOffset = CGSizeMake(0,2);
    self.progressView.layer.shadowOpacity = 1;
    self.progressView.layer.shadowRadius = 6;
    self.progressView.trackTintColor = UIColorHex_(0xffffff,0.6);
    self.progressView.progressTintColor = KThemeColor;
    self.progressView.progress = 0;
    [self.customNavigationBar addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@52);
        make.centerY.mas_equalTo(closeBtn);
        make.height.mas_equalTo(@8);
        make.right.mas_equalTo(@-64);
    }];
    self.progressView.hidden = YES;
    
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.font = JPUIFontInterRegular(14);
    self.countLabel.textColor = KFontBlackColor;
    self.countLabel.textAlignment = NSTextAlignmentRight;
    [self.customNavigationBar addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-20);
        make.height.mas_equalTo(@17);
        make.centerY.mas_equalTo(weakSelf.progressView);
    }];
    self.countLabel.hidden = YES;
    
    self.swipeableView = [[ZLSwipeableView alloc]initWithFrame:CGRectMake(20, kYM_NAVIGATIONBAR_HEIGHT+16, self.currentAvailableWidth-40,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-16-74)];
    self.swipeableView.dataSource = self;
    self.swipeableView.delegate = self;
    self.swipeableView.numberOfActiveViews = 3;
    self.swipeableView.viewAnimator = self;
    self.swipeableView.allowedDirection = ZLSwipeableViewDirectionAll;
    self.swipeableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.swipeableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.swipeableView];
    
    
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.pageIndicatorTintColor = KbgColor;
    self.pageControl.currentPageIndicatorTintColor = KThemeColor;
    self.pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    self.pageControl.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(@-90);
        make.height.mas_equalTo(@8);
        make.centerX.mas_equalTo(weakSelf.view);
    }];

}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          // 获取当前可用宽度并更新布局
           self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
           self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
           self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
           CGFloat h636 = [DeviceUtils getAdaptedWidthForDesignWidth:636 andCurrentAvailableWidth:self.currentAvailableWidth];
           if(h636 > self.currentAvailableHeight){
            h636 = self.currentAvailableHeight;
            }
            self.topImageView.frame = CGRectMake(0, 0, self.currentAvailableWidth,h636);
            NSInteger current_index = 0;
            if(self.sel_index < 3){
                current_index = self.sel_index+3;
            }else{
                current_index = self.sel_index-3;
            }
            BOOL isBack = NO;//是否翻了卡片
            BOOL isKnow = YES;//是否选了知道
            if(self.isTest == YES){
                NSArray *activeViews = [self.swipeableView activeViews];
                if (activeViews.count > 0) {
                    WordsCardView *currentCardView = (WordsCardView *)[activeViews firstObject];
                    if(currentCardView.knowBgView.hidden == NO){
                        isBack = YES;
                        if(currentCardView.knownBtn.selected == NO){
                            isKnow = NO;
                        }
                    }
                }
            }
            self.isRefreshWidth = YES;
            [self.swipeableView removeFromSuperview];
            self.swipeableView = nil;
            [self createSwipeableView];
            if(self.dataArr.count > 0){
                // 重新加载视图
                self.sel_index = 0;
                [self.swipeableView loadViewsIfNeeded];
                //滑动到之前的卡片位置
                for(NSInteger i = 0;i < self.dataArr.count+1;i++){
                    if(i == current_index){
                        if(self.isTest == NO){
                            self.pageControl.currentPage = i;
                        }
                        break;
                    }
                    [self.swipeableView swipeTopViewToLeftNoDynamic];
                }
                if(isBack == YES){
                    //测试有翻了背面
                    NSArray *activeViews = [self.swipeableView activeViews];
                    if (activeViews.count > 0) {
                        WordsCardView *currentCardView = (WordsCardView *)[activeViews firstObject];
                        if(isKnow == YES){
                            [currentCardView correctBtnClick];
                        }else{
                            [currentCardView errorBtnClick];
                        }
                    }
                }
                self.isRefreshWidth = NO;
            }
            
        });
    }
}

-(void)createSwipeableView{
    self.swipeableView = [[ZLSwipeableView alloc]initWithFrame:CGRectMake(20, kYM_NAVIGATIONBAR_HEIGHT+16, self.currentAvailableWidth-40,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-16-74)];
    self.swipeableView.dataSource = self;
    self.swipeableView.delegate = self;
    self.swipeableView.numberOfActiveViews = 3;
    self.swipeableView.viewAnimator = self;
    self.swipeableView.allowedDirection = ZLSwipeableViewDirectionAll;
    self.swipeableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.swipeableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.swipeableView];
    [self.view bringSubviewToFront:self.pageControl];
}

#pragma mark - 获取测试单词组
-(void)loadTestData{
    self.wordTestManager.wordIds = self.wordIds;
    [self.wordTestManager loadData];
}

#pragma mark - 获取下一组单词
-(void)loadNextWordsData{
    self.wordListOrderManager.courseId = self.courseModel.courseId;
    [self.wordListOrderManager loadData];
}

#pragma mark - 开始背词
-(void)loadReciteWordData{
    self.reciteWordManager.courseId = self.courseModel.courseId;
    [self.reciteWordManager loadData];
}

#pragma mark - 返回
-(void)closeBtnClick{
    __weak typeof(self)weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        if(weakSelf.refrehBlock){
            weakSelf.refrehBlock();
        }
    }];
}


#pragma mark - ZLSwipeableViewDataSource
- (UIView *)nextViewForSwipeableView:(ZLSwipeableView *)swipeableView{
    //背词
    if(self.isTest == NO){
        if (self.sel_index >= self.dataArr.count+1) {
            self.sel_index = 0;
        }
    }
    
    WordsCardView *cardView = [[WordsCardView alloc] initWithFrame:CGRectMake(0,0, swipeableView.frame.size.width,swipeableView.frame.size.height) andCurrentAvailableWidth:self.currentAvailableWidth andCurrentAvailableHeight:self.currentAvailableHeight];
    cardView.currentAvailableWidth = self.currentAvailableWidth;
    cardView.currentAvailableHeight = self.currentAvailableHeight;
    cardView.delegate = self;
    self.sel_index++;
    if(self.isTest == NO){
        //背词
        cardView.isTest = NO;
        if((self.sel_index-1) < self.dataArr.count){
            cardView.model = self.dataArr[self.sel_index-1];
            cardView.isLast = NO;
            NSInteger count = MIN(self.dataArr.count,self.swipeableView.numberOfActiveViews);
            if (self.initCount < count) {
                //刚开始初始化读一次
                if(self.sel_index == 1){
                    if((!self.isjump)&&(!self.isRefreshWidth)){
                        if(cardView.model.audio&&![cardView.model.audio isEqualToString:@""]){
                            [cardView playAudio:cardView.model.audio];
                        }else{
                            if((cardView.model.pronunciation)&&(![cardView.model.pronunciation isEqualToString:@""])){
                                if((cardView.model.writing)&&(cardView.model.isReadWriting)&&([cardView.model.isReadWriting isEqualToString:@"1"]||cardView.model.isReadWriting.integerValue == 1)){
                                    [cardView speakJapaneseText:cardView.model.writing];
                                }else{
                                    [cardView speakJapaneseText:cardView.model.pronunciation];
                                }
                            }else{
                                if((cardView.model.writing)&&(![cardView.model.writing isEqualToString:@""])){
                                    [cardView speakJapaneseText:cardView.model.writing];
                                }
                            }
                        }
                    }
                    if(self.isjump == YES){
                        self.isjump = NO;
                        self.firstCardView = cardView;
                    }
                }
                self.initCount++;
            }
        }else{
            cardView.isLast = YES;
            cardView.wordArr = self.dataArr;
        }
    }else{
        //背词里的测试
        if((self.sel_index-1) < self.dataArr.count){
            cardView.isTest = YES;
            cardView.model = self.dataArr[self.sel_index-1];
            if(self.sel_index == 1){
                if([cardView.model.mode isEqualToString:@"2"]&&(!self.isRefreshWidth)){
                    //自动读
                    if(cardView.model.audio&&![cardView.model.audio isEqualToString:@""]){
                        [cardView playAudio:cardView.model.audio];
                    }else{
                        if((cardView.model.pronunciation)&&(![cardView.model.pronunciation isEqualToString:@""])){
                            if((cardView.model.writing)&&(cardView.model.isReadWriting)&&([cardView.model.isReadWriting isEqualToString:@"1"]||cardView.model.isReadWriting.integerValue == 1)){
                                [cardView speakJapaneseText:cardView.model.writing];
                            }else{
                                [cardView speakJapaneseText:cardView.model.pronunciation];
                            }
                        }else{
                            if((cardView.model.writing)&&(![cardView.model.writing isEqualToString:@""])){
                                [cardView speakJapaneseText:cardView.model.writing];
                            }
                        }
                    }
                }
            }
        }
    }
    // 设置前三个视图的布局
    if (self.sel_index <= 3) {
        CGFloat xOffset = (self.sel_index - 1) * 12.0;
        CGFloat yOffset = (self.sel_index - 1) * 12.0;
        CGPoint offset = CGPointMake(xOffset, yOffset);
        CGRect frame = swipeableView.bounds;
        CGFloat widthReduction = (self.sel_index - 1) * 24.0;
        frame.origin.x += xOffset;
        frame.size.width -= widthReduction;
        cardView.frame = frame;
        CGFloat scale = 1.0 - ((self.sel_index - 1) * 0.1);
        cardView.transform = CGAffineTransformScale(cardView.transform, scale, 1.0);
        cardView.type = self.sel_index;
        [self rotateAndTranslateView:cardView
                           forDegree:0
                         translation:CGPointZero
                            duration:0
                  atOffsetFromCenter:offset
                       swipeableView:swipeableView];
    } else {
        cardView.type = 3;
        cardView.transform = CGAffineTransformIdentity; // 重置视图的变换
    }
    
    return cardView;
}

- (void)animateView:(UIView *)view
              index:(NSUInteger)index
              views:(NSArray<UIView *> *)views
      swipeableView:(ZLSwipeableView *)swipeableView {
    NSTimeInterval duration = 0.4;
    CGFloat xOffset = index * 12.0;
    CGFloat yOffset = index * 12.0;
    CGPoint translation = CGPointMake(xOffset, yOffset);
    if (index >= 3) {
        // 大于等于第三个视图的处理
        WordsCardView *thirdView = (WordsCardView*)views[2]; // 第三个视图的索引是2
        thirdView.type = 3;
        CGRect thirdFrame = thirdView.frame;
        view.frame = thirdFrame;
        [self rotateAndTranslateView:view
                           forDegree:0
                         translation:translation
                            duration:duration
                  atOffsetFromCenter:CGPointZero
                       swipeableView:swipeableView];
    } else {
        // 前三个视图的处理
        WordsCardView *cardView = (WordsCardView*)views[index];
        CGFloat widthReduction = index * 24.0;
        CGPoint offset;
        if (index == 0) {
            // 第一张视图保持初始宽度
            cardView.type = 1;
            view.frame = swipeableView.bounds;
            offset = CGPointMake(0, 0);
        } else {
            // 第二和第三张视图逐渐减小宽度
            CGRect frame = swipeableView.bounds;
            CGFloat widthDifference = widthReduction/2.0;
            frame.origin.x += widthDifference;
            frame.size.width -= widthReduction;
            view.frame = frame;
            
            // 设置前两张视图的偏移量和缩放
            CGFloat scale = 0.9;
            if(index == 2){
                scale = 0.8;
                cardView.type = 3;
            }else{
                cardView.type = 2;
            }
            offset = CGPointMake(widthDifference, -CGRectGetHeight(swipeableView.bounds) * 0.3);
            view.transform = CGAffineTransformScale(view.transform,scale, 1.0);
        }
        
        [self rotateAndTranslateView:view
                           forDegree:0
                         translation:translation
                            duration:duration
                  atOffsetFromCenter:offset
                       swipeableView:swipeableView];
    }
}

- (void)rotateAndTranslateView:(UIView *)view
                     forDegree:(float)degree
                   translation:(CGPoint)translation
                      duration:(NSTimeInterval)duration
            atOffsetFromCenter:(CGPoint)offset
                 swipeableView:(ZLSwipeableView *)swipeableView {
    [UIView animateWithDuration:duration
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         CGPoint center = CGPointMake(CGRectGetMidX(swipeableView.bounds), CGRectGetMidY(swipeableView.bounds));
                          if(translation.x > 0){
                              center = CGPointMake(CGRectGetMidX(swipeableView.bounds)-translation.x, CGRectGetMidY(swipeableView.bounds));
                          }
                         view.center = [swipeableView convertPoint:center fromView:swipeableView];
                         CGAffineTransform transform = CGAffineTransformMakeTranslation(offset.x, offset.y);
                         transform = CGAffineTransformRotate(transform, degree * M_PI / 180.0);
                         transform = CGAffineTransformTranslate(transform, -offset.x, -offset.y);
                         transform = CGAffineTransformTranslate(transform, translation.x, translation.y);
                         view.transform = transform;
                     }
                     completion:nil];
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView didSwipeView:(UIView *)view inDirection:(ZLSwipeableViewDirection)direction{
    
    if(self.isTest == NO){

      if(self.pageControl.currentPage < self.dataArr.count){
         self.pageControl.currentPage = self.pageControl.currentPage+1;
      }else{
         self.pageControl.currentPage = 0;
      }
        if((self.pageControl.currentPage != self.dataArr.count)&&(!self.isRefreshWidth)){
            // 获取当前活动视图列表
            NSArray *activeViews = [swipeableView activeViews];
            if (activeViews.count > 0) {
                WordsCardView *currentCardView = (WordsCardView *)[activeViews firstObject];
                if ([currentCardView isKindOfClass:[WordsCardView class]]) {
                    if(currentCardView.model.audio&&![currentCardView.model.audio isEqualToString:@""]){
                        [currentCardView playAudio:currentCardView.model.audio];
                    }else{
                        if((currentCardView.model.pronunciation)&&(![currentCardView.model.pronunciation isEqualToString:@""])){
                            if((currentCardView.model.writing)&&(currentCardView.model.isReadWriting)&&([currentCardView.model.isReadWriting isEqualToString:@"1"]||currentCardView.model.isReadWriting.integerValue == 1)){
                                [currentCardView speakJapaneseText:currentCardView.model.writing];
                            }else{
                                [currentCardView speakJapaneseText:currentCardView.model.pronunciation];
                            }
                        }else{
                            if((currentCardView.model.writing)&&(![currentCardView.model.writing isEqualToString:@""])){
                                [currentCardView speakJapaneseText:currentCardView.model.writing];
                            }
                        }
                    }
                }
            }
        }
    }else{
        // 获取当前活动视图列表
        NSArray *activeViews = [swipeableView activeViews];
        if (activeViews.count > 0&&(!self.isRefreshWidth)) {
            WordsCardView *currentCardView = (WordsCardView *)[activeViews firstObject];
            if ([currentCardView isKindOfClass:[WordsCardView class]]&&[currentCardView.model.mode isEqualToString:@"2"]) {
                if(currentCardView.model.audio&&![currentCardView.model.audio isEqualToString:@""]){
                    [currentCardView playAudio:currentCardView.model.audio];
                }else{
                    if((currentCardView.model.pronunciation)&&(![currentCardView.model.pronunciation isEqualToString:@""])){
                        if((currentCardView.model.writing)&&(currentCardView.model.isReadWriting)&&([currentCardView.model.isReadWriting isEqualToString:@"1"]||currentCardView.model.isReadWriting.integerValue == 1)){
                            [currentCardView speakJapaneseText:currentCardView.model.writing];
                        }else{
                            [currentCardView speakJapaneseText:currentCardView.model.pronunciation];
                        }
                    }else{
                        if((currentCardView.model.writing)&&(![currentCardView.model.writing isEqualToString:@""])){
                            [currentCardView speakJapaneseText:currentCardView.model.writing];
                        }
                    }
                }
            }
        }
    }
}


#pragma mark - WordsCardViewDelegate
//提交错误
-(void)applyErrorTap:(WordsCardView *)wordsCardView{
    WordErrorViewController *vc = [[WordErrorViewController alloc]init];
    vc.wordModel = wordsCardView.model;
    [self.navigationController pushViewController:vc animated:YES];
}

//收藏 取消收藏
-(void)collectTap:(WordsCardView *)wordsCardView andIsCollect:(BOOL)isCollect{
    self.collectWordsCardView = wordsCardView;
    if(isCollect == NO){
        //收藏
        [self wordCollectWithWordId:wordsCardView.model.wordId];
    }else{
        //取消收藏
        [self deleteWordCollectWithCollectId:wordsCardView.model.collectId];
    }
}
//开始测试
-(void)beginTestTap:(WordsCardView *)wordsCardView{
     [self loadTestData];
}

//下一步
-(void)nextTap:(WordsCardView *)wordsCardView andIsKnow:(BOOL)isKnow{
    [self updateWordState:wordsCardView.model andIsKnow:isKnow];
  
}

#pragma mark - 修改单词状态
-(void)updateWordState:(WordListModel*)model andIsKnow:(BOOL)isKnow{
    self.stateTestUpdateManager.testId = model.testId;
    self.stateTestUpdateManager.correct = isKnow == YES?@"1":@"0";
    self.stateTestUpdateManager.wordIds = self.wordIds;
    [self.stateTestUpdateManager loadData];
}

#pragma mark - 单词收藏
-(void)wordCollectWithWordId:(NSString*)wordId{
    self.collectSaveManager.wordId = wordId;
    self.collectSaveManager.type = @"1";
    [self.collectSaveManager loadData];
}
#pragma mark - 取消收藏
-(void)deleteWordCollectWithCollectId:(NSString*)collectId{
    self.collectDeleteManager.collectId = collectId;
    [self.collectDeleteManager loadData];
}

#pragma mark - 刷新卡片
- (void)refreshSwipeableViewData{
    // 清空当前的所有视图
    for (UIView *view in self.swipeableView.activeViews) {
        [view removeFromSuperview];
    }
    
    if(self.dataArr.count > 0){
        // 重置数据索引
        self.sel_index = 0;
        // 重新加载视图
        [self.swipeableView loadViewsIfNeeded];
        // 更新 UIPageControl 的 currentPage
        if(self.isTest == NO){
            self.pageControl.currentPage = self.sel_index;
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
   
    
    if([manager isEqual:self.reciteWordManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        self.wordIds = [NSMutableString string];
        for(NSInteger i = 0;i < arr.count;i++){
            WordListModel *model = arr[i];
            [self.wordIds appendString:model.wordId];
            if(i < arr.count-1){
                [self.wordIds appendString:@","];
            }
        }
        self.initCount = 0;
        if(self.dataArr.count > 0){
            if(self.dataArr.count >= 2){
                self.swipeableView.numberOfActiveViews = 3;
            }else{
                self.swipeableView.numberOfActiveViews = self.dataArr.count+1;
            }
            [self refreshSwipeableViewData];
            self.pageControl.numberOfPages = self.dataArr.count+1;
            self.pageControl.currentPage = 0;
        }else{
            self.pageControl.numberOfPages = 0;
            self.pageControl.currentPage = 0;
        }
    }
    
    if([manager isEqual:self.wordListOrderManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        self.wordIds = [NSMutableString string];
        for(NSInteger i = 0;i < arr.count;i++){
            WordListModel *model = arr[i];
            [self.wordIds appendString:model.wordId];
            if(i < arr.count-1){
                [self.wordIds appendString:@","];
            }
        }
        self.initCount = 0;
        self.isTest = NO;
        self.swipeableView.allowedDirection = ZLSwipeableViewDirectionAll;
        if(arr.count == 0){
            //没有了 去小结
            SummaryViewController *vc = [[SummaryViewController alloc]init];
            vc.isTotal = YES;
            vc.wordIds = self.wordIds;
            vc.courseModel = self.courseModel;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            self.isjump = YES;
            self.searchBgView.hidden = NO;
            self.pageControl.hidden = NO;
            self.countLabel.hidden = YES;
            self.progressView.hidden = YES;
            if(self.dataArr.count > 0){
                if(self.dataArr.count >= 2){
                    self.swipeableView.numberOfActiveViews = 3;
                }else{
                    self.swipeableView.numberOfActiveViews = self.dataArr.count+1;
                }
                [self refreshSwipeableViewData];
                self.pageControl.numberOfPages = self.dataArr.count+1;
                self.pageControl.currentPage = 0;
            }else{
                self.pageControl.numberOfPages = 0;
                self.pageControl.currentPage = 0;
            }
            //有 去小结
            SummaryViewController *vc = [[SummaryViewController alloc]init];
            vc.isTotal = NO;
            vc.wordIds = self.wordIds;
            vc.courseModel = self.courseModel;
            [self.navigationController pushViewController:vc animated:YES];
            __weak typeof(self)weakSelf = self;
            [vc setReadBlock:^{
                //下一组测试点击回来 读第一个单词
                if(weakSelf.firstCardView){
                    if(weakSelf.firstCardView.model.audio&&![weakSelf.firstCardView.model.audio isEqualToString:@""]){
                        [weakSelf.firstCardView playAudio:weakSelf.firstCardView.model.audio];
                    }else{
                        if((weakSelf.firstCardView.model.pronunciation)&&(![weakSelf.firstCardView.model.pronunciation isEqualToString:@""])){
                            if((weakSelf.firstCardView.model.writing)&&(weakSelf.firstCardView.model.isReadWriting)&&([weakSelf.firstCardView.model.isReadWriting isEqualToString:@"1"]||weakSelf.firstCardView.model.isReadWriting.integerValue == 1)){
                                [weakSelf.firstCardView speakJapaneseText:weakSelf.firstCardView.model.writing];
                            }else{
                                [weakSelf.firstCardView speakJapaneseText:weakSelf.firstCardView.model.pronunciation];
                            }
                        }else{
                            if((weakSelf.firstCardView.model.writing)&&(![weakSelf.firstCardView.model.writing isEqualToString:@""])){
                                [weakSelf.firstCardView speakJapaneseText:weakSelf.firstCardView.model.writing];
                            }
                        }
                    }
                }
            }];
        }
    }
    
    if([manager isEqual:self.collectSaveManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        WordListModel *model = self.collectWordsCardView.model;
        model.isCollect = @"1";
        model.collectId = [NSString stringWithFormat:@"%@",dic[@"data"][@"collectId"]];
        self.collectWordsCardView.model = model;
        if(self.isTest == YES){
            //如果是测试模式的话，需要把三种模式的卡片都修改它的收藏状态
            for(NSInteger i = 0; i< self.dataArr.count;i++){
                WordListModel *model0 = self.dataArr[i];
                if([model0.wordId isEqualToString:model.wordId]){
                    model0.isCollect = @"1";
                    model0.collectId = [NSString stringWithFormat:@"%@",dic[@"data"][@"collectId"]];
                    [self.dataArr replaceObjectAtIndex:i withObject:model0];
                }
            }
            
            NSArray *activeViews = [self.swipeableView activeViews];
            if (activeViews.count > 0) {
                for(NSInteger i = 0;i < activeViews.count;i++){
                    WordsCardView *currentCardView = (WordsCardView *)activeViews[i];
                    if ([currentCardView isKindOfClass:[WordsCardView class]]) {
                        if([currentCardView.model.wordId isEqualToString:model.wordId]){
                            //同一个单词的 修改它的收藏状态
                            WordListModel *model2 = currentCardView.model;
                            model2.isCollect = @"1";
                            model2.collectId = [NSString stringWithFormat:@"%@",dic[@"data"][@"collectId"]];
                            currentCardView.model = model2;
                        }
                    }
                }
            }
            
        }else{
            for(NSInteger i = 0; i< self.dataArr.count;i++){
                WordListModel *model0 = self.dataArr[i];
                if([model0.wordId isEqualToString:model.wordId]){
                    [self.dataArr replaceObjectAtIndex:i withObject:model];
                    break;
                }
            }
        }
    }
    
    if([manager isEqual:self.collectDeleteManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        WordListModel *model = self.collectWordsCardView.model;
        model.isCollect = @"0";
        model.collectId = @"";
        self.collectWordsCardView.model = model;
        if(self.isTest == YES){
            for(NSInteger i = 0; i < self.dataArr.count;i++){
                WordListModel *model0 = self.dataArr[i];
                if([model0.wordId isEqualToString:model.wordId]){
                    model0.isCollect = @"0";
                    model0.collectId = @"";
                    [self.dataArr replaceObjectAtIndex:i withObject:model0];
                }
            }
            
            
            NSArray *activeViews = [self.swipeableView activeViews];
            if (activeViews.count > 0) {
                for(NSInteger i = 0;i < activeViews.count;i++){
                    WordsCardView *currentCardView = (WordsCardView *)activeViews[i];
                    if ([currentCardView isKindOfClass:[WordsCardView class]]) {
                        if([currentCardView.model.wordId isEqualToString:model.wordId]){
                            //同一个单词的 修改它的收藏状态
                            WordListModel *model2 = currentCardView.model;
                            model2.isCollect = @"0";
                            model2.collectId = @"";
                            currentCardView.model = model2;
                        }
                    }
                }
            }
            
        }else{
            for(NSInteger i = 0; i< self.dataArr.count;i++){
                WordListModel *model0 = self.dataArr[i];
                if([model0.wordId isEqualToString:model.wordId]){
                    [self.dataArr replaceObjectAtIndex:i withObject:model];
                    break;
                }
            }
        }
    }
    
    if([manager isEqual:self.wordTestManager]){
        NSDictionary *dic = manager.response.content;
        self.isTest = YES;
        self.sumCount = [NSString stringWithFormat:@"%@",dic[@"data"][@"sumCount"]];
        NSString *correctCount = [NSString stringWithFormat:@"%@",dic[@"data"][@"correctCount"]];
        self.correctCount = correctCount?correctCount.integerValue:0;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"userWord"]];
        if(arr.count == 0){
            //测完了  获取下一组单词
            self.isTest = NO;
            self.swipeableView.allowedDirection = ZLSwipeableViewDirectionAll;
            [self loadNextWordsData];
        }else{
            self.dataArr = [NSMutableArray arrayWithArray:arr];
            self.swipeableView.allowedDirection = ZLSwipeableViewDirectionNone;//不让滑动
            if(self.dataArr.count >= 3){
                self.swipeableView.numberOfActiveViews = 3;
            }else{
                self.swipeableView.numberOfActiveViews = self.dataArr.count;
            }
            self.initCount = 0;
            [self refreshSwipeableViewData];
            self.searchBgView.hidden = YES;
            self.pageControl.numberOfPages = 0;
            self.pageControl.currentPage = 0;
            self.pageControl.hidden = YES;
            self.countLabel.hidden = NO;
            self.progressView.hidden = NO;
            self.countLabel.text = [NSString stringWithFormat:@"%ld/%@",self.correctCount,self.sumCount];
            if(self.sumCount.integerValue == 0){
                self.progressView.progress = 0;
            }else{
                self.progressView.progress = self.correctCount/self.sumCount.floatValue;
            }
            CGFloat w = [self getStringWidthWithText:self.countLabel.text font:self.countLabel.font viewHeight:17];
            [self.progressView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-w-32);
            }];
        }
    }
    
    if([manager isEqual:self.stateTestUpdateManager]){
        //滑动下一张卡片
        if(self.stateTestUpdateManager.correct.integerValue == 1){
            self.correctCount++;
            self.countLabel.text = [NSString stringWithFormat:@"%ld/%@",self.correctCount,self.sumCount];
            if(self.sumCount.integerValue == 0){
                self.progressView.progress = 0;
            }else{
                self.progressView.progress = self.correctCount/self.sumCount.floatValue;
            }
            CGFloat w = [self getStringWidthWithText:self.countLabel.text font:self.countLabel.font viewHeight:17];
            [self.progressView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-w-32);
            }];
        }
        self.testCount++;
        if(self.testCount == self.dataArr.count){
            //测完一组的一次 重新获取数据看看有没有错误的
            self.testCount = 0;
            [self.dataArr removeAllObjects];
            [self loadTestData];
        }else{
            [self.swipeableView swipeTopViewToLeft];
        }
        
    }
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
        if (self.nui) {
            [self.nui nui_tts_release];
            self.nui = nil;
        }
        [self NuiTtsInit];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


@end
